package com.junmo.oauth.config.security;

import com.junmo.oauth.config.security.authentication.MyAuthenticationProvider;
import com.junmo.oauth.config.security.handler.*;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;

@Configuration
@EnableWebSecurity  //启动web安全性
// 开启方法级的权限注解
// 设置后控制器层的方法前的@PreAuthorize("hasRole('admin')") 注解才能起效
@EnableGlobalMethodSecurity(prePostEnabled = true)
@AllArgsConstructor
public class    WebSecurityConfig extends WebSecurityConfigurerAdapter {
    private MyUserDetailService myUserDetailService;
    //认证异常处理
    private MyAuthenticationEntryPoint myAuthenticationEntryPoint;
    //授权异常处理
    private MyAccessDeniedHandler myAccessDeniedHandler;
    //登录陈功处理
    private MyAuthenticationSuccessHandler myAuthenticationSuccessHandler;
    //登录失败处理
    private MyAuthenticationFailureHandler myAuthenticationFailureHandler;
    //登出处理
    private MyLogoutSuccessHandler myLogoutSuccessHandler;
    //自定义认证逻辑
    private MyAuthenticationProvider myAuthenticationProvider;


    @Autowired
    PasswordEncoder passwordEncoder;
    // 注入AuthenticationManager接口，启用OAuth2密码模式
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth
                .authenticationProvider(myAuthenticationProvider)
                .userDetailsService(myUserDetailService)
                .passwordEncoder(passwordEncoder);
    }


    @Override
    public void configure(WebSecurity web) throws Exception {
        //解决静态资源被拦截的问题
        web.ignoring().antMatchers("/favicon.ico");
        web.ignoring().antMatchers("/error");
        super.configure(web);
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource(){
        return httpServletRequest -> {
            CorsConfiguration cfg = new CorsConfiguration();
            cfg.addAllowedHeader("*");
            cfg.addAllowedMethod("*");
            cfg.addAllowedOrigin("*");
            cfg.setAllowCredentials(true);
//            cfg.checkOrigin("http://localhost:9528");
            return cfg;
        };
    }


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //关闭csrf验证
        http.csrf().disable()
                // 基于token，所以不需要session  如果基于session 则表使用这段代码
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                .and()
                //对请求进行认证  url认证配置顺序为：1.先配置放行不需要认证的 permitAll() 2.然后配置 需要特定权限的 hasRole() 3.最后配置 anyRequest().authenticated()
                .authorizeRequests()
                .antMatchers("/oauth/**","/login","/logout").permitAll()

                .anyRequest().authenticated()

                .and().exceptionHandling().authenticationEntryPoint(myAuthenticationEntryPoint) .accessDeniedHandler(myAccessDeniedHandler)

                .and().formLogin().loginProcessingUrl("/login").successHandler(myAuthenticationSuccessHandler).failureHandler(myAuthenticationFailureHandler).permitAll()

                .and().logout().logoutUrl("/logout").logoutSuccessHandler(myLogoutSuccessHandler).invalidateHttpSession(true).permitAll()

                .and().rememberMe().tokenValiditySeconds(3600)
            ;
        // 禁用缓存
        http.headers().cacheControl();
    }

}
